from tppt.lib.actions import TemplateAction
from tppt.lib.actions import get_actions_details
from tppt.lib.actions.url import get_action_url 
from tppt.lib import utils
from tppt.lib import HumanizeContext
from tppt.lib import exceptions


class Action(TemplateAction):
	image_url='/static/images/icon_details.gif'
	template='lib/base_details.html'
	
	def get_name(self):
		return 'details'
	
	def perform_template(self):
		entity=self.object
		sections=entity.get_details_sections()
		sections_params=[]
		for section in sections:
			section.assign_action(self)
			params=section.get_params()
			if 'template' in params:
				raise exceptions.TemplateNameError('Cannot use "template" parameter in details section.')
			params['template']=section.template
			sections_params.append(params)
		params['sections']=sections_params
		return params


class Section(object):
	template = None
	def assign_action(self, action):
		self.action=action
		
	@property
	def entity(self):
		return self.action.object
	@property
	def request(self):
		return self.action.request
	
	def get_params(self):
		return {}
	
class PropertyListSection(Section):
	template='lib/details/property_list.html'
	humanize_context=HumanizeContext(use_html=True)
	
	def get_params(self):
		entity=self.entity
		model=entity.__class__
		cols=model.get_fields_dict().values()
		params={'entity': self.entity, 'cols': cols}
		return params

class ActionsSection(Section):
	template='lib/details/actions.html'
	
	def get_params(self):
		entity=self.entity
		actions=get_actions_details(entity)
		actions=utils.filter(lambda x:x['name']!='details', actions)
		
		params={'actions': actions}
		return params

class ReferringEntitiesSection(Section):
	template='lib/details/referring_entities.html'
	humanize_context=HumanizeContext(use_html=True)
	max_object_count=10
	def __init__(self, model, field):
		self.ref_model=model
		self.ref_field=field
	
	def get_referring_entities_query_set(self):
		model=self.ref_model
		fld_name=self.ref_field.name
		query_set=model.objects.all().filter_ref(fld_name, self.entity)
		return query_set
		
	def get_params(self):
		fld=self.ref_field
		model=self.ref_model

		ref_qs=self.get_referring_entities_query_set()
		entities_count=ref_qs.count()
		
		entities=ref_qs[:self.max_object_count]
		
		all_url=get_action_url('index', ref_qs)
		
		params={
			'referer': model,
			'referring_property': fld,
			'all_url': all_url,
			'entities': entities,
			}

		if entities_count>len(entities):
			params['remaining']=entities_count-len(entities)
		return params
		
		
